package cpoo.painting;

import java.awt.Dimension;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;

import cpoo.exceptions.MotionException;
import cpoo.util.Loger;

public class DapplesCreator {
	private FrameStorage frameStorage;
	private FrameInfo[] framesInfos;
	public DapplesCreator (File frameStorrageFile, File affineTransformsFile, File objectsFile, Dimension frameSize) throws MotionException{
		frameStorage = new FrameStorage(frameStorrageFile);
		Loger transformsLog = new Loger(affineTransformsFile);
		AffineTransform[] transforms = transformsLog.readAffineTransformations();
		Loger objectsLog = new Loger(objectsFile);
		framesInfos = objectsLog.readObjects(transforms, frameSize);
		
		System.out.println("frames infos loaded: "+framesInfos.length);
		for (int i=0; i<framesInfos.length; i++){
			int index = getNextIndex(i, i);
			while(!framesInfos[i].allreadyVanished() && index != -1){
				//System.out.println("Resolving dependancy of frames #"+i+" and #"+index);
				framesInfos[i].fillWithInfoFrom(framesInfos[index]);
				index = getNextIndex(i, index);
			}
			System.out.println("Dapple info constructed for frame #"+i+" klatka zalezy od lacznej ilosci "+framesInfos[i].numberOfDependantFrames()+" klatek");
			framesInfos[i].constructDapple(frameStorage);
			System.out.println("Dapple construction finished");
		}
	}
	
	public void coverWithDapple(BufferedImage frame, long frameNumber){
		if (frameNumber-1 < framesInfos.length){
			framesInfos[(int)frameNumber-1].coverWithDapple(frame);
		}
	}
	
	private int getNextIndex(int startIndex, int previousIndex){
		if (framesInfos.length < 2){
			return -1;
		}
		if (startIndex == previousIndex){
			if (startIndex == 0){
				return 1;
			} else {
				return startIndex -1;
			}
		} else {
			int ret = startIndex + startIndex - previousIndex;
			if (previousIndex < startIndex){
				if (ret+1 < framesInfos.length){
					return ret+1;
				} else {
					return previousIndex -1;
				}
			} else {
				if (ret > 0){
					return ret;
				} else {
					if (previousIndex +1 < framesInfos.length){
						return previousIndex +1;
					} else {
						return -1;
					}
				}
			}
		}
	}
}
